package cn.zxh.improvement.jpa.support;

import cn.zxh.improvement.common.core.exceptions.ValidationException;
import cn.zxh.improvement.common.core.validate.group.ValidateGroup;
import org.springframework.util.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public abstract class BaseEntityOperation implements EntityOperation {

    static final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    public <T> void doValidate(T t, Class<? extends ValidateGroup> group) {
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(t, group, Default.class);
        if (!CollectionUtils.isEmpty(constraintViolations)) {
            Map<String, String> collect = constraintViolations.stream()
                    .collect(Collectors.toMap(constraintViolation -> constraintViolation.getPropertyPath().toString(),
                            ConstraintViolation::getMessage,
                            (oldV, newV) -> newV));
            throw new ValidationException(collect.toString());
        }
    }
}
